package ee.serge.util;

import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.ui.HorizontalPanel;

public class SliderWithTextBox extends HorizontalPanel implements HasValueChangeHandlers<Void> {

   private final int min;
   private final int max;
   private EventBus bus;
   private Slider slider;
   private BTextBox textBox;
   
   public SliderWithTextBox(int min, int max) {
      this.min = min;
      this.max = max;
      bus = new SimpleEventBus();
      slider = new Slider(min, max);
      add(slider);
      textBox = new BTextBox(min);
      add(textBox);
      slider.addValueChangeHandler(new SliderChangeHandler());
      slider.addReleaseHandler(new SliderReleaseHandler());
      textBox.addKeyUpHandler(new TextChangeHandler());
   }
   
   private void dispatchValueChangeEvent() {
      ValueChangeEvent.fire(this, null);
   }
   
   private class SliderChangeHandler implements ValueChangeHandler<Integer> {
      @Override
      public void onValueChange(ValueChangeEvent<Integer> event) {
         textBox.setText(event.getValue());
         //dispatchValueChangeEvent();
      }
   }
   
   private class SliderReleaseHandler implements ValueChangeHandler<Integer> {
      @Override
      public void onValueChange(ValueChangeEvent<Integer> event) {
         textBox.setText(event.getValue());
         dispatchValueChangeEvent();
      }
   }
 
   private class TextChangeHandler implements KeyUpHandler {

      @Override
      public void onKeyUp(KeyUpEvent event) {
         String val = textBox.getText();
         if (val.length() == 0) {
            val = "0";
         }
         try {
            int nrVal = Integer.valueOf(val);
            if (nrVal > max || nrVal < min) throw new Exception();
            slider.setValue(nrVal);
            dispatchValueChangeEvent();
            textBox.removeStyleName("error");
         } catch (Exception e) {
            textBox.addStyleName("error");
         }
      }
   }

   public String getText() {
      return textBox.getText();
   }
   
   public void setValue(int val) {
      slider.setValue(val);
      textBox.setText(String.valueOf(val));
   }

   @Override
   public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Void> handler) {
      return bus.addHandler(ValueChangeEvent.getType(), handler);
   }
   
   @Override
   public void fireEvent(GwtEvent<?> event) {
      bus.fireEvent(event);
   }

}
